package com.heima.article.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heim.file.MinIoTemplate;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.common.freemarker.FreemarkerGenerator;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
@Autowired
private ApArticleMapper apArticleMapper;

    @Override
    public ResponseResult load(ArticleHomeDto dto) {
        List<ApArticle> apArticles = apArticleMapper.loadArticle(dto, 1);
        return ResponseResult.okResult(apArticles);
    }

    @Override
    public ResponseResult loadmore(ArticleHomeDto dto) {
        List<ApArticle> apArticles = apArticleMapper.loadArticle(dto, 1);
        return ResponseResult.okResult(apArticles);
    }

    @Override
    public ResponseResult loadnew(ArticleHomeDto dto) {

        List<ApArticle> apArticles = apArticleMapper.loadArticle(dto, 2);
        return ResponseResult.okResult(apArticles);
    }
@Autowired
private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private FreemarkerGenerator freemarkerGenerator;
    @Autowired
    private MinIoTemplate minIoTemplate;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Async
    @Override
    public void generate(Long articleId) {
        //查询ApArticleContent获取content
        LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApArticleContent::getArticleId,articleId);
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(wrapper);
        if (apArticleContent==null){
            log.warn("无该文章");
            return;
        }
        //创建map将content数据赋值到map中
        Map<String, Object> map = new HashMap<>(1);

       map.put("content", JSON.parseArray(apArticleContent.getContent()));
    //调用freemarker插件生成html
        //括号里的内容，模板文件名  数据
        InputStream generate = freemarkerGenerator.generate("article.ftl", map);


        //调用minio插件上传html
        //文件流
        String url = minIoTemplate.uploadFile("", articleId + ".html", generate, "html");


        ApArticle apArticle = apArticleMapper.selectById(articleId);
        if (apArticle==null){
            log.warn("文章为空");
            return;
        }
        apArticle.setStaticUrl(url);
        //更新ApArticle修改里面static_url字段
        apArticleMapper.updateById(apArticle);


    }
@Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ResponseResult saveArticle(ArticleDto dto) {
       //1入参判空
     if(dto==null){
         return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
     }

        Long id = dto.getId();
        String content = dto.getContent();

    //组装article
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);
        //2.判断dto里面的id是否存在
        if (id==null) {

            //3，不存在则新增

            //3插入article表
            int insert = apArticleMapper.insert(apArticle);
            if (insert<1){ //说明没插入成功
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"文章新增失败");
            }

            //3插入article_config表
            ApArticleConfig config = new ApArticleConfig();
            config.setIsDown(false);
            config.setIsDelete(false);
            config.setIsForward(true);
            config.setIsComment(true);
            config.setArticleId(apArticle.getId());
            int configInsertResult = apArticleConfigMapper.insert(config);
            if (configInsertResult <1){ //返回失败
                log.warn("文章配置插入失败");
                throw new RuntimeException("文章配置插入失败");

            }

            //3插入content表
            ApArticleContent articleContent = new ApArticleContent();
            articleContent.setContent(content);
            articleContent.setArticleId(apArticle.getId());

            int contentResult = apArticleContentMapper.insert(articleContent);
            if (contentResult<1){
                log.warn("文章内容表插入失败");
                throw new RuntimeException("文章内容表插入失败");
            }


            generate(apArticle.getId());
            return ResponseResult.okResult(apArticle.getId());

        }else {
            //4若存在
            //4修改article表
            int updateResult = apArticleMapper.updateById(apArticle);
            if (updateResult<1){

                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"文章修改失败");
            }

            //4修改article_content表
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setContent(content);

            LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApArticleContent::getArticleId,id);

            int contentUpdateResult = apArticleContentMapper.update(apArticleContent, wrapper);
            if (contentUpdateResult<1){
            log.warn("文章内容表修改失败");
            throw new RuntimeException("文章内容表修改失败");
            }

            //调用详情
            generate(id);

            //5将article返回回去
            return ResponseResult.okResult(id);
        }


    }


}
